<?php
namespace app\components;
use Yii;
use yii\web\Response;
/**
 * This is a comment.
 */
class API{
    const ok=0;                 ///执行正确
    const Parameters_error=101;////参数错误
    const authority_error=    102;//权限错误
    const weizhi_error=103;//未知错误
    const guest=2;///表示游客
    private static $apilist=false;
    public static $errormsg_array=array();///错误信息数组
    public static $errormsg='';//错误信息
    private function getapi(){
        return require(dirname(__FILE__).'/config/api_list.php');
    }

    /**
     * 把数组的错误信息转换为字符串
    */
    public static function tostr($array){
           $error='';
         foreach($array as $v){
            $error.=$v[0];
        }
        return $error;
    }

    /**
     * 赋值数组错误信息
     */
    public static function setArrtyError($arrayerror){
        self::$errormsg=self::tostr($arrayerror);
    }


    public static function add_error($msg){
        self::$errormsg_array[]=$msg;
    }
    
    
    public static function get_errorstr(){
           $error='';
         foreach(self::$errormsg_array as $v){
            $error.=$v[0];
        }
        return $error;
    }

        public function getlist(){
        if(self::$apilist===false){           
            $data=$this->getapi();
            foreach ($data as $key=>$vo){
                $data[$key]['url']=Yii::app()->createUrl('api/'.$vo['action']);
            }
            self::$apilist=$data;
        }
        return self::$apilist;
    }

    public function tree(){
        $tree=array();
        foreach ($this->getlist() as $vo){
            if(!isset($tree[$vo['class']]))
            {   $tree[$vo['class']]=array(); }
            $tree[$vo['class']][]=$vo;
        }
        
           $params=array();
        foreach($tree as $key=>$vo){
            $params[]=array(
                'text'=>$key,
                'children'=>$this->_flist($vo)
            );
        }
        return $params;
    }
     private function _flist($list){
        $data=array();
        foreach ($list as $vo){
            $data[]=array(
                'text'=>$vo['name'],
                'htmlOptions'=>array(
                    'data'=>'('.  json_encode($vo).')',
                    'class'=>'cursor'
                    ),
            );
        }
        return $data;
    }
    
    public function run($act){
        if($act==false){
            $this->echo_json(API::Parameters_error,'参数错误');
        }
        if($apiinfo=$this->access($act)){///检查权限
            API::set_post_info($act);
         $strphp='return '.$apiinfo['php'].';'; 
       $data=eval($strphp);
        API::set_post_info($act,$data);
            if($data!==false){
                $this->echo_json(API::ok,$data); 
            }else{
                if(API::$errormsg==''){
                    if(API::$errormsg_array===array()){
                         API::$errormsg='未知错误';
                    }else{
                       $error='';
                        foreach( API::$errormsg_array as $k=>$v){
                            $error.=$v[0];
                        }
                        API::$errormsg=$error;
                    }  
                }
                 $this->echo_json(API::weizhi_error,API::$errormsg); 
            }
        }else{
           $this->echo_json(API::authority_error,'没有权限'); 
        }
    }
    private function access($act){
///     print_r($this->get_act_api());
    ///    echo Yii::app()->user->id;
        $apiinfo=$this->get_act_api($act);
        if($apiinfo===false)
            { return false;}
       if($apiinfo['users']=='*'){         
           return $apiinfo;
       }elseif($apiinfo['users']=='@'){
          
           return Yii::app()->user->isGuest?false:$apiinfo;
       }elseif($apiinfo['users']=='admin'){
      //     return false;
           return $this->isadmin()?$apiinfo:false;
       }     
        //     print_r($apiinfo); 
        return false;
    }

    private function get_act_api($act=0){
        $list=Yii::app()->cache->get('APIlist');
        if($list==false||YII_DEBUG){
           $list=$this->_getactapi();
           Yii::app()->cache->set('APIlist',$list);
        }
        if($act===0){
            return $list;
        }else{
            return isset($list[$act])?$list[$act]:false;
        }
        return $list;
    }
    private function _getactapi(){
        $api=  $this->getapi();
      //  print_r($api);
        $ad=array();
        foreach ($api as $key=>$vo){
            $ad[$vo['action']]=$vo;
        }
        return $ad;
    }



    public static function echo_json($code=0,$data='0'){
        Yii::$app->response->format =  Response::FORMAT_RAW;
        Yii::$app->response->headers->set('Content-Type','application/json; charset=UTF-8');
       /// Yii::$app->response->headers->set('Cosssssse','afffffffn');
       // header('Content-Type','application/json');//Content-Type: application/json
        Yii::$app->response->send();
        if($data===true){
            $data='ok';
        }
        if($code==200){
            $code=0;
        }
        $js=array();
        $js['code']=$code;
        $js['data']=$data;
        if($code!=0&&$code!=200){
            $js['data']=null;
            $js['msg']=$data;
        }
        echo json_encode($js);
        Yii::$app->end();
        // return json_encode($js);
      //  Yii::$app->end();
    }
    
    public static function url_login(){
     ////   Yii::app()->user->returnUrl=$returnUrl;
       return   Yii::app()->createUrl('home/public/login');
    }
    
    private function isadmin(){
        return Yii::app()->user->isadmin();/*
          $auth=Yii::app()->authManager;
          $ss=$auth->getRoles(Yii::app()->user->id);
          if(isset($ss['Administrator']))
          {  return true;}
          else
          {   return false;}*/
    }
    




    public static function ADMINISTRATOR(){ 
        if(defined('ADMINISTRATOR')&&ADMINISTRATOR){
           return true; 
        }
       
        
        return false;
    }
    
    
    
    
    public static function get_post_info(){
        if(isset(Yii::app()->session['service_info'])){
            return Yii::app()->session['service_info'];
        }else{
            return false;
        }
    }
     public static function set_post_info($act,$data=array()){///写入发送信息
     if($act=='get_service_post_info')         return; 
        if(defined('YII_DEBUG')&&YII_DEBUG){
            Yii::app()->session['service_info']=array(
                'post'=>API::format_html(print_r($_POST,true)),
                'get'=>API::format_html(print_r($_GET,true)), 
                'time'=>date("Y-m-d H:i:s",time()),
                'return'=>API::format_html(print_r($data,true))
                );
        }
    }
    
    public static function format_html($msg_area){ 
        $msg_area =  str_replace("\n","<br>",$msg_area);//换行 
        
        return  ($msg_area);
    }
    /*
    public static function set_return_info($act,$data){
          if($act=='get_service_post_info')         return; 
        if(defined('YII_DEBUG')&&YII_DEBUG){
         //   Yii::app()->session['service_info']['return']='';//print_r($data,true);
            print_r( Yii::app()->session['service_info']);
        }
    }*/
    
     
}